package com.uyayo.framework.web.util;

import com.uyayo.framework.web.constants.WebConstants;
import com.uyayo.framework.web.exception.CaptchaException;
import com.uyayo.framework.web.exception.CaptchaIsNullException;
import com.uyayo.framework.web.exception.CaptchaTimeOutException;

import java.util.Date;
import java.util.regex.Pattern;

public class VerifyCaptchaUtil {
	private final static String REGEX = "[@ `~!#$%^&*()+=|{}':;',//[//]<>/?~！#￥%……&*（）——+|{}【】‘；：”“’。，、？]";

	private final static Pattern STRING_PATTERN = Pattern.compile(REGEX);

	private VerifyCaptchaUtil() {
	}

	/**
	 * 验证码校验
	 * 默认验证码超时时间 5 分钟
	 *
	 * @param captcha           验证码
	 * @param exitCodeObject    session中保存的验证码
	 * @param captchaTimeObject 验证码记录的时间
	 * @throws CaptchaException        验证码为空
	 * @throws CaptchaTimeOutException 验证码超时
	 * @throws CaptchaException        验证码错误
	 */
	public static void verifyCaptcha(String captcha, Object exitCodeObject, Object captchaTimeObject) throws CaptchaException, CaptchaTimeOutException, CaptchaIsNullException {
		verifyCaptcha(captcha, exitCodeObject, captchaTimeObject, WebConstants.CAPTCHA_TIMEOUT);
	}

	/**
	 * 验证码校验
	 * 默认验证码超时时间 5 分钟
	 *
	 * @param captcha           验证码
	 * @param exitCodeObject    session中保存的验证码
	 * @param captchaTimeObject 验证码记录的时间
	 * @param timeOut           验证码超时时间 毫秒
	 * @throws CaptchaException        验证码为空
	 * @throws CaptchaTimeOutException 验证码超时
	 * @throws CaptchaException        验证码错误
	 */
	public static void verifyCaptcha(String captcha, Object exitCodeObject, Object captchaTimeObject, long timeOut) throws CaptchaTimeOutException, CaptchaException, CaptchaIsNullException {
		if (null == exitCodeObject || null == captchaTimeObject) {
			throw new CaptchaIsNullException("Captcha is null");
		}
		String exitCode = (String) exitCodeObject;
		long captchaTime = (Long) captchaTimeObject;
		if (new Date().getTime() - captchaTime > timeOut) {
			throw new CaptchaTimeOutException("captcha timeout");
		}
		if (!exitCode.equalsIgnoreCase(captcha)) {
			throw new CaptchaException("captcha exitCode error");
		}
	}


	/**
	 * 验证码校验超时
	 * 默认验证码超时时间 5 分钟
	 *
	 * @param exitCodeObject    session中保存的验证码
	 * @param captchaTimeObject 验证码记录的时间
	 * @param timeOut           验证码超时时间 毫秒
	 * @throws CaptchaException        验证码为空
	 * @throws CaptchaTimeOutException 验证码超时
	 * @throws CaptchaException        验证码错误
	 */
	public static void verifyCaptchaTime(Object exitCodeObject, Object captchaTimeObject, long timeOut) throws CaptchaException, CaptchaTimeOutException {
		if (null == exitCodeObject || null == captchaTimeObject) {
			throw new CaptchaException("Captcha is null");
		}
		long captchaTime = (Long) captchaTimeObject;
		if (new Date().getTime() - captchaTime > timeOut) {
			throw new CaptchaTimeOutException("captcha timeout");
		}
	}
}
